#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "shm.hpp"
#define _FIFO_PATH_ "."
#define _FIFO_NAME_ "fifo"

class fifofile
{
public:
    fifofile(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        // 创建管道文件
        _fifoname = path + '/' + name;
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            std::cerr << "mkfifo failed" << std::endl;
            exit(1);
        }
        std::cout << "mkfifo success" << std::endl;
    }
    ~fifofile()
    {
        unlink(_fifoname.c_str());
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class file
{
public:
    file(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _filename = path + '/' + name;
    }
    ~file()
    {
        _close();
    }
    bool _readopen()
    {
        _fd = open(_filename.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open failed" << std::endl;
            return false;
        }
        std::cout << "readopen succcess" << std::endl;
        return true;
    }
    bool _writeopen()
    {
        _fd = open(_filename.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open failed" << std::endl;
            return false;
        }
        std::cout << "write open success" << std::endl;
        return true;
    }
    int _read()
    {
        char ch;
        if (_fd < 0)
            -1;
        int x = read(_fd, &ch, 1);
        if (x < 0)
        {
            EXIT("read");
        }
        else if (x == 0)
            return 0;
        return x;
    }
    int _write()
    {
        char ch;
        if (_fd < 0)
            return -1;
        int n = write(_fd, &ch, 1);
        if (n < 0)
        {
            std::cerr << "read failed" << std::endl;
            exit(1);
        }
        return n;
    }
    void _close()
    {
        if (_fd >= 0)
            close(_fd);
    }
    void Print()
    {
        std::cout << _filename << ", _fd : " << _fd << std::endl;
    }

private:
    std::string _path;
    std::string _name;
    std::string _filename;
    int _fd;
};